package edu.unmsm.fisi.taller2.mvcdemo.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.unmsm.fisi.taller2.mvcdemo.controller.app.ShowRecordRequestHandler;
import edu.unmsm.fisi.taller2.mvcdemo.controller.app.UsuariosRequestHandler;

public class ControllerServlet extends HttpServlet {
    private Map<String, RequestHandler> hh = new HashMap<String, RequestHandler>();

    @Override
    public void init() throws ServletException {
    	hh.put("/login.html", new ShowRecordRequestHandler());
    	hh.put("/showInfo.html", new ShowRecordRequestHandler());
    	hh.put("/listadoUsuario.html", new UsuariosRequestHandler());
    }

    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    	String sp = request.getServletPath();
        System.out.println("servlet path = " + sp);

        RequestHandler rh = (RequestHandler) hh.get(sp);
        if (rh == null ) {
     	   response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {
     	   String viewURL = rh.handleRequest(request, response);
     	   if (viewURL == null) {
     		   // El RequestHandler ha terminado la produccion: no hacer nada
     	   } else {
     		   // El RequestHandler nos indica la vista a utilizar
     		   request.getRequestDispatcher(viewURL).forward(request, response);
     	   }
        }
    }

}
